var URLDialog = (function(){
    /**
     * 构造函数.
     */
    var _linkManageDialog = function(cfg){
        var _this = this;
        this.setProps({
            isFullscreen : true,
            size : {
                width : 760,
                height : 650
            }
        });
        this.addLinkForm();
        this.addPageDesigner();
    }.extend(ujs.ui.Dialog);    
    /**
     * 初始化表单. 
     */
    _linkManageDialog.prototype.addLinkForm = function(){
        var _this = this;
        this.addDialogLayer('form', URLDialogView.linkForm, function($dialogContent) {
            $dialogContent.find('.urlOnly').remove();
            _this.$form = $dialogContent;
            _this.$form.find('.urlTitle').parent().addClass('required');
            $dialogContent.addClass('dialogLayerCenter').addClass('urlForm');
            _this.$selectUserTip = $dialogContent.find('.su');            
            //member selector
            _this.memberSelector = new MemberSelector($dialogContent.find('.memberSelector2'), {
                size : {
                    width : 554,
                    height : 90
                },
                treeType : {
                    survey : 'survey',
                    eventurl : 'event',
                    web : 'web',
                    page : 'page'
                }[_this.config['relType']],    
                mode : 'expand',
                clickable : (function(){
                    if(_this.config['mode'] === 'edit'){                        
                        var entity = page.urlStore.getItem(_this.config['ueid']);
                        if(entity.perm.adm && entity.creator.id == ujs.util.session.getCurrentUserID()){
                            return true;
                        } else {
                            _this.$selectUserTip.remove();
                            return false;
                        }
                    } else {
                        //添加模式
                        return true;
                    }
                })(),
                exclusion : [ujs.util.session.getCurrentUserID()],            
                events : {
                    change : function(){
                        _this.toggleAdvancedProps();
                    }
                }
            });                                      
            _this.iconObj = $dialogContent.find('#icon').singleImgUploader({
                style : 'innerIcon',
                width : 60,
                height : 60,
                toolbar : false,          
                uploadImmediately : false,
                value : ({
                        survey : '/ujs/app/im/images/index/survey.png',
                        eventurl : '/ujs/app/im/images/index/event.png',
                        web : '/ujs/app/im/images/link.png',
                        page : '/ujs/app/im/images/index/customPageLink.png'
                }[_this.config['relType']])
                                
            }).data('singleImgUploader');
                        
            if(_this.config['mode'] === 'edit'){
                _this.initFormData(_this.config['ueid']);                
            } else {
                $dialogContent.find('.formInput.urlTitle').val('new ' + {
                        survey : 'survey',
                        eventurl : 'event',
                        web : 'webpage',
                        page : 'webpage'
                }[_this.config['relType']]);
            }
            
            $dialogContent.find('.closeBtn').click(function(){
                _this.hideMask();
                _this.hideDialogLayer('form');
            });
            
            $dialogContent.find('.saveBtn').click(function(){                
                if(_this.$wrapper.find('.saveBtn').text() == 'ok'){
                    var formValues = ujs.browser.form.getValues(_this.$form);
                    _this.$titlePane.text(formValues['title']);
                    _this.hideMask();
                    _this.hideDialogLayer('form');
                    return false;
                }    
                                            
                if(!ujs.browser.form.validate(_this.$form)){
                    return false;
                }
                                
                var formValues = ujs.browser.form.getValues(_this.$form),
                    ueid = formValues['id'];
                    
                    
                var $saveBtn2 = $(this);
                
                var d = _this.getFormData();    
                if(d){
                    _this.showMask(0);
                    var $layer = _this.getDialogLayer('form');
                    
                    $layer.css('z-index', 9);
                    $(this).disable();  //避免重复提交.
                       
                    page.biz.uploadURLEntity2(ueid || 'new', d, function(data){
                        _this.showMask(1);
                        bubble.msg('{0} {1} successfully.'.format(ueid ? 'Update' : 'Create', {
                            survey : 'survey',
                            eventurl : 'event',
                            web : 'link',
                            page : 'page'
                        }[_this.config['relType']]));
                        _this.remove();
                        
                        if(_this.config['mode'] == 'edit'){
                            try{
                                page.contentCardLayout.getActiveItem().$iframe.get(0).contentWindow.location.reload();
                            }catch(e){}
                        }
                    }, _this, function(){
                        $layer.css('z-index', 9999999);
                        $saveBtn2.enable();
                        _this.hideMask();
                    });
                }
                return false;
            });    
        });
    };
   
    //-----------------------------------------------------------------------------------------------------
    
    /**
     * 初始化 PageDesigner. 
     */
    _linkManageDialog.prototype.addPageDesigner = function(){
        var _this = this;
        this.addDialogContent(URLDialogView.surveyPage, function($dialogContent){      
            
            var entity = page.urlStore.getItem(_this.config['ueid']);
            var etitle = '';
            if(entity){
                etitle = window.encodeURIComponent(entity['name']);
            }
                  
            _this.surveyPageDesigner = PageDesigner.create($dialogContent, {
                type : _this.config['relType'],                                
                etitle : etitle,                
                onDesignerLoad : function(){     
                    _this.initPageDesigner();  
                    //发布时逻辑.
                    arguments[0].contentWindow.pageDesigner.on('publish', function(){
                        _this.showMask('');
                        var innerWin = _this.$wrapper.find('iframe').get(0).contentWindow; 
                        if(!innerWin.pageDesigner.hasChild(innerWin.PageDesigner.ButtonElement)){                            
                            if(_this.config['relType'] != 'web' && _this.config['relType'] != 'page'){
                                var buttonElement = innerWin.pageDesigner.createNode('ButtonElement', {
                                    text : _this.config['relType'] === 'eventurl' ? 'Join' : 'Submit'
                                });
                                innerWin.pageDesigner.children[0].addChild(buttonElement); 
                            }
                        }           
                        
                        _this.$wrapper.find('.urlForm').css('height', '410px');     
                        _this.$wrapper.find('.saveBtn').text('submit');        
                        
                        var $form = _this.getDialogLayer('form'),
                            winWidth = $(_this.$dialogBody).width(),
                            winHeight = $(_this.$dialogBody).height();
                            
                        $form.css({
                            left : Math.max((winWidth - $form.outerWidth()) / 2, 0),
                            top : Math.max((winHeight - $form.outerHeight()) / 3, 0)
                        });
                        
                        _this.$wrapper.find('.titleInput').hide();
                        _this.$wrapper.find('.membersInput').show();
                        _this.showDialogLayer('form');
                    });  
                    
                    //发布时逻辑.
                    arguments[0].contentWindow.pageDesigner.on('changeTitle', function($titlePane){
                        _this.$titlePane  = $titlePane;
                        _this.showMask('');  
                        
                        _this.$wrapper.find('.urlForm').css('height', '150px');
                        _this.$wrapper.find('.saveBtn').text('ok');
                           
                        var $form = _this.getDialogLayer('form'),
                            winWidth = $(_this.$dialogBody).width(),
                            winHeight = $(_this.$dialogBody).height();
                        $form.css({
                            left : Math.max((winWidth - $form.outerWidth()) / 2, 0),
                            top : Math.max((winHeight - $form.outerHeight()) / 2, 0)
                        });
                        
                        _this.$wrapper.find('.titleInput').show();
                        _this.$wrapper.find('.membersInput').hide();
                        _this.showDialogLayer('form');
                    });  
                    
                    // if(_this.config['mode'] != 'edit'){  
                         // _this.$titlePane  = $titlePane;
                        // _this.showMask('');  
//                         
                        // _this.$wrapper.find('.urlForm').css('height', '150px');
                        // _this.$wrapper.find('.saveBtn').text('ok');
//                            
                        // var $form = _this.getDialogLayer('form'),
                            // winWidth = $(_this.$dialogBody).width(),
                            // winHeight = $(_this.$dialogBody).height();
                        // $form.css({
                            // left : Math.max((winWidth - $form.outerWidth()) / 2, 0),
                            // top : Math.max((winHeight - $form.outerHeight()) / 2, 0)
                        // });
//                         
                        // _this.$wrapper.find('.titleInput').show();
                        // _this.$wrapper.find('.membersInput').hide();
                        // _this.showDialogLayer('form');
                    // }
                    
                    arguments[0].contentWindow.pageDesigner.on('save', function(){
                            var formValues = ujs.browser.form.getValues(_this.$form),
                                ueid = formValues['id'];                                
                                                        
                            var d = _this.getFormData();    
                            if(d){
                                _this.showMask(0);                                                      
                                page.biz.uploadURLEntity(ueid || 'new', d, function(data){
                                    _this.showMask(1);
                                    bubble.msg('{0} {1} successfully.'.format(ueid ? 'Update' : 'Create', {
                                        survey : 'survey',
                                        eventurl : 'event',
                                        web : 'link',
                                        page : 'page'
                                    }[_this.config['relType']]));
                                    _this.remove();
                                    
                                    if(_this.config['mode'] == 'edit'){
                                        try{
                                            page.contentCardLayout.getActiveItem().$iframe.get(0).contentWindow.location.reload();
                                        }catch(e){}
                                    }              
                                                          
                                }, _this, function(){         
                                    _this.hideMask();
                                });
                            }
                            return false;
                    });         
                }
            });  
            var result = _this.surveyPageDesigner.init();
            if(!result){
                _this.initPageDesigner();
            }                      
        }); 
    };
    
    _linkManageDialog.prototype.initPageDesigner = function(){
        var _this = this;
        if(_this.customPageID && _this.currentEntityID){
            
            $.ajax({                
                url : '/apis/page/{0}?e={1}&t={2}&etitle='.format(_this.customPageID, _this.currentEntityID, Date.now()),
                success : function(data){                            
                    _this.surveyPageDesignerObj = _this.getCard('designer').find('iframe').get(0).contentWindow.pageDesigner;
                    _this.surveyPageDesignerObj.parseSurveyData(data);
                },
                error : function(xhr,status,error){ }
            });
        } 
    };
    
    //------------------------------------------------------------------------------------------------
    
    /**
     * 初始化表单数据.
     */
    _linkManageDialog.prototype.initFormData = function(urlID){
        var _this = this;
        this.showMask('Loading ...');
        $.ajax({
            url : '/apis/url/{topicEntityId}'.format({
                topicEntityId : urlID
            }),
            success : ujs.hr(function(msg){                        
                var urlEntity = msg['ue'],
                    isCustomPage = urlEntity.url.indexOf('page://') === 0,
                    customPageID = urlEntity.url.replace('page://', '');
                    
                _this.currentEntityID = urlEntity['id'];                
                _this.customPageID = customPageID;                
                ujs.browser.form.setValues(this.$form, urlEntity);                    
                _this.memberSelector.addMembers(urlEntity['participants']).setAdmins(urlEntity['adminUserIds']);
                _this.hideMask();
            })
        });
    };   
    /**
     * 获取表单数据.
     */
    _linkManageDialog.prototype.getFormData = function(){  
        //url基础数据.  
        var formValues = ujs.browser.form.getValues(this.$form),
            members = this.memberSelector.getUserAndGroup(),
            json = {
                url : JSON.stringify({
                    type : this.config['relType'],
                    title : formValues['title'] || formValues['url'],
                    ugids : members['groups'],
                    uids : members['users'].concat(ujs.util.session.getCurrentUserID()), 
                    auids : this.memberSelector.getAdmins().concat(ujs.util.session.getCurrentUserID()),                
                    url : formValues['url']    
                })                     
            };
            
        //自定义页面数据.
        var pageData = this.surveyPageDesigner.getPageData();
        
        try{
            if(!pageData.json.items.length || ( pageData.json.items[0].control && $.isEmptyObject(pageData.json.items[0].control))){
                bubble.msg('Page is not complete.');
                return false;
            }
        }catch(e){}
        
        if(pageData){
            json['page'] = JSON.stringify(pageData['json']);
            if(pageData['files']){
                for(var file in pageData['files']){
                    json[file] = pageData['files'][file];
                }
            }
        }
        //url图标上传.
        var formData = Object.toFormData(json);        
        this.iconObj.fillupImageFiles(formData, [[200,200]]);
        
        return formData;
    };
    
    //------------------------------------------------------------------------------------------------
    
    _linkManageDialog.prototype.toggleAdvancedProps = function(){   
        var users = this.memberSelector.getUserAndGroup()['users'];
        if(users.length){            
            this.$selectUserTip.show();
        } else {
            this.$selectUserTip.hide();            
        }
    };    
    
    return _linkManageDialog;    
})();